package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author cisimu
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.判断老人是否已经入住
        //根据老人身份证号和状态查询老人信息，如果能查询到数据，说明老人已经入住
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1)
        );
        if (ObjectUtil.isNotEmpty(elder)) {
            //查询不为空，说明老人已经入住
            throw new RuntimeException("该老人已经入住");
        }
        //2.修改床位状态
        //老人未入住，将床位状态改为已入住
        //现根据床位id查询床位信息，获取床位对象，再将床位状态设置为已入住，在根据id更新床位。否则还要新建床位实体类对象
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.新增或更新老人
        elder = saveOrUpdateElder(checkInApplyDto, bed);
        //4.新增签约合同
        saveContract(checkInApplyDto, elder);
        //5.新增入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto, elder, bed);
        //6.新增入住配置信息
        saveCheckInConfig(checkInApplyDto,checkIn);
    }

    /**
     * 新增入住配置信息
     * @param checkInApplyDto
     * @param checkIn
     */
    private void saveCheckInConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param checkInApplyDto
     */
    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder,Bed bed) {
        CheckIn checkIn = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约合同
     * @param checkInApplyDto
     */
    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        String code = CodeGenerator.generateContractNumber();
        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(), Contract.class);
        contract.setContractNumber(code);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setStatus(0);
        contractMapper.insert(contract);
    }


    /**
     * 新增或更新老人信息
     * @param checkInApplyDto
     */
    private Elder saveOrUpdateElder(CheckInApplyDto checkInApplyDto,Bed bed) {
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        Elder newElder = BeanUtil.toBean(checkInElderDto, Elder.class);
        newElder.setBedNumber(bed.getBedNumber());
        newElder.setBedId(bed.getId());
        newElder.setStatus(1);
        //根据身份证号和状态（不为1）查询老人信息，查询出来说明之前住过，就更新老人信息，查不出来就是新增老人信息
        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .ne(Elder::getStatus, 1)
        );
        if (ObjectUtil.isNotEmpty(oldElder)) {
            //不为空，就更新老人信息
            newElder.setId(oldElder.getId());
            elderMapper.updateById(newElder);
        }else {
            //为空，就新增老人信息
            elderMapper.insert(newElder);
        }
        return newElder;
    }


    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {
        //1.查询老人信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        //计算老人的年龄
        checkInElderVo.setAge(DateUtil.ageOfNow(elder.getBirthday()));
        //2.查询老人家属信息
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        //3.查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId, checkIn.getId())
        );
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        //4.查询签约合同信息
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, checkIn.getElderId())
        );
        return new CheckInDetailVo(checkInElderVo,elderFamilyVos,checkInConfigVo,contract);
    }
}
